package Netty_basic.echo;


import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import javax.swing.*;
import java.nio.charset.Charset;
import java.util.Scanner;

public class echo_client {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group=new NioEventLoopGroup();
        Channel channel = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                System.out.println(byteBuf.toString(Charset.defaultCharset()));
                            }
                        });
                    }
                }).connect("localhost", 8080).sync().channel();

        System.out.println(channel);

        channel.closeFuture().addListener(future -> {
            group.shutdownGracefully();
        });

        new Thread(()->{
            while (true){
                Scanner scanner=new Scanner(System.in);
                String s = scanner.nextLine();
                if (s.equals("q")){
                    channel.close();
                    break;
                }else {
                    channel.writeAndFlush(s);
                }
            }
        }).start();

    }
}
